<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择所属仓库" clearable style="width: 240px" @change="() => handleWarehouseChange('query')">
          <el-option
            v-for="warehouse in warehouseOptions"
            :key="warehouse.warehouseId"
            :label="warehouse.warehouseName"
            :value="warehouse.warehouseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属库区" prop="areaId">
        <el-tree-select
          v-model="queryParams.areaId"
          :data="areaOptions"
          :props="{ label: 'areaName', value: 'areaId', children: 'children' }"
          value-key="areaId"
          placeholder="请选择所属库区"
          clearable
          style="width: 240px"
          :disabled="!queryParams.warehouseId"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="库位编码" prop="locationCode">
        <el-input
          v-model="queryParams.locationCode"
          placeholder="请输入库位编码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位类型" prop="locationType">
        <el-select v-model="queryParams.locationType" placeholder="请选择库位类型" clearable style="width: 240px">
          <el-option
            v-for="dict in locationTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库位状态" prop="locationStatus">
        <el-select v-model="queryParams.locationStatus" placeholder="请选择库位状态" clearable style="width: 240px">
          <el-option
            v-for="dict in locationStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['wms:location:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:location:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:location:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['wms:location:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="locationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库位ID" align="center" prop="locationId" v-if="false" />
      <el-table-column label="所属仓库" align="center" prop="warehouseName" />
      <el-table-column label="所属库区" align="center" prop="areaName">
        <template #default="scope">
          <span>{{ scope.row.areaPath ? scope.row.areaPath.split(',').map(id => getAreaName(id)).join(' / ') : scope.row.areaName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库位编码" align="center" prop="locationCode" />
      <el-table-column label="库位类型" align="center" prop="locationType">
        <template #default="scope">
          <dict-tag :options="locationTypeOptions" :value="scope.row.locationType"/>
        </template>
      </el-table-column>
      <el-table-column label="库位状态" align="center" prop="locationStatus">
        <template #default="scope">
          <dict-tag :options="locationStatusOptions" :value="scope.row.locationStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="最大承重(kg)" align="center" prop="maxWeight" />
      <el-table-column label="最大体积(m³)" align="center" prop="maxVolume" />
      <el-table-column label="坐标" align="center">
        <template #default="scope">
          X:{{ scope.row.positionX }} Y:{{ scope.row.positionY }} Z:{{ scope.row.positionZ }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:location:edit']"
          >修改</el-button>
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:location:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库位信息对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="locationRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择所属仓库" @change="() => handleWarehouseChange('form')">
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.warehouseId"
              :label="warehouse.warehouseName"
              :value="warehouse.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属库区" prop="areaId">
          <el-tree-select
            v-model="form.areaId"
            :data="areaOptions"
            :props="{ label: 'areaName', value: 'areaId', children: 'children' }"
            value-key="areaId"
            placeholder="请选择所属库区"
            :disabled="!form.warehouseId"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="库位编码" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入库位编码" />
        </el-form-item>
        <el-form-item label="库位类型" prop="locationType">
          <el-select v-model="form.locationType" placeholder="请选择库位类型">
            <el-option
              v-for="dict in locationTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库位状态" prop="locationStatus">
          <el-radio-group v-model="form.locationStatus">
            <el-radio
              v-for="dict in locationStatusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大承重" prop="maxWeight">
              <el-input-number v-model="form.maxWeight" :precision="2" :step="0.1" placeholder="请输入最大承重" />
              <span class="ml5">kg</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大体积" prop="maxVolume">
              <el-input-number v-model="form.maxVolume" :precision="3" :step="0.1" placeholder="请输入最大体积" />
              <span class="ml5">m³</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="X轴坐标" prop="positionX">
              <el-input-number v-model="form.positionX" :precision="0" placeholder="X轴" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Y轴坐标" prop="positionY">
              <el-input-number v-model="form.positionY" :precision="0" placeholder="Y轴" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Z轴坐标" prop="positionZ">
              <el-input-number v-model="form.positionZ" :precision="0" placeholder="Z轴" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Location">
import { listLocation, getLocation, delLocation, addLocation, updateLocation, exportLocation } from "@/api/wms/base/location";
import { treeArea } from "@/api/wms/base/area";
import { listWarehouse } from "@/api/wms/base/warehouse";

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 库位信息表格数据
const locationList = ref([]);
// 仓库下拉框数据
const warehouseOptions = ref([]);
// 库区树形数据
const areaOptions = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

// 库位类型选项
const locationTypeOptions = ref([
  { value: "1", label: "普通货架" },
  { value: "2", label: "地堆" },
  { value: "3", label: "立体库" },
  { value: "4", label: "临时区" }
]);

// 库位状态选项
const locationStatusOptions = ref([
  { value: "1", label: "空闲" },
  { value: "2", label: "占用" },
  { value: "3", label: "锁定" }
]);

// 库区名称缓存
const areaNameMap = ref({});

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  warehouseId: null,  // 添加仓库ID
  areaId: null,
  locationCode: null,
  locationType: null,
  locationStatus: null
});

// 表单参数
const form = ref({
  locationId: null,
  warehouseId: null,  // 添加仓库ID
  areaId: null,
  locationCode: null,
  locationType: null,
  locationStatus: "1",  // 默认空闲
  maxWeight: null,
  maxVolume: null,
  positionX: null,
  positionY: null,
  positionZ: null,
  remark: null
});

// 表单校验
const rules = ref({
  warehouseId: [
    { required: true, message: "所属仓库不能为空", trigger: "change" }
  ],
  areaId: [
    { required: true, message: "所属库区不能为空", trigger: "change" }
  ],
  locationCode: [
    { required: true, message: "库位编码不能为空", trigger: "blur" }
  ],
  locationType: [
    { required: true, message: "库位类型不能为空", trigger: "change" }
  ],
  locationStatus: [
    { required: true, message: "库位状态不能为空", trigger: "change" }
  ]
});

/** 查询库区树形列表 */
function getAreaOptions(warehouseId) {
  const query = {};
  if (warehouseId) {
    query.warehouseId = warehouseId;
  }
  treeArea(query).then(response => {
    // 如果没有选择仓库，清空库区树
    if (!warehouseId) {
      areaOptions.value = [];
      areaNameMap.value = {};
      return;
    }
    // 添加仓库名称作为顶级节点
    const warehouse = warehouseOptions.value.find(w => w.warehouseId === warehouseId);
    if (warehouse && response.data && response.data.length > 0) {
      areaOptions.value = response.data;
      // 更新库区名称缓存
      updateAreaNameMap(response.data);
    } else {
      areaOptions.value = [];
      areaNameMap.value = {};
    }
  });
}

/** 更新库区名称缓存 */
function updateAreaNameMap(areas) {
  areas.forEach(area => {
    areaNameMap.value[area.areaId] = area.areaName;
    if (area.children && area.children.length > 0) {
      updateAreaNameMap(area.children);
    }
  });
}

/** 获取库区名称 */
function getAreaName(areaId) {
  return areaNameMap.value[areaId] || '';
}

/** 查询仓库下拉列表 */
function getWarehouseOptions() {
  listWarehouse().then(response => {
    warehouseOptions.value = response.rows;
  });
}

/** 仓库选择框变化事件 */
function handleWarehouseChange(type) {
  if (type === 'form') {
    // 表单内仓库选择变化
    getAreaOptions(form.value.warehouseId);
    form.value.areaId = null;
  } else {
    // 查询条件仓库选择变化
    getAreaOptions(queryParams.value.warehouseId);
    queryParams.value.areaId = null;
  }
}

/** 查询库位信息列表 */
function getList() {
  loading.value = true;
  listLocation(queryParams.value).then(response => {
    locationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    locationId: null,
    warehouseId: null,  // 添加仓库ID
    areaId: null,
    locationCode: null,
    locationType: null,
    locationStatus: "1",  // 默认空闲
    maxWeight: null,
    maxVolume: null,
    positionX: null,
    positionY: null,
    positionZ: null,
    remark: null
  };
  proxy.resetForm("locationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.locationId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getWarehouseOptions();
  open.value = true;
  title.value = "添加库位信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getWarehouseOptions();
  const locationId = row.locationId || ids.value[0];
  getLocation(locationId).then(response => {
    form.value = response.data;
    // 获取库区列表
    getAreaOptions(form.value.warehouseId);
    open.value = true;
    title.value = "修改库位信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["locationRef"].validate(valid => {
    if (valid) {
      if (form.value.locationId != null) {
        updateLocation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLocation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const locationIds = row.locationId || ids.value;
  proxy.$modal.confirm('是否确认删除库位信息编号为"' + locationIds + '"的数据项？').then(function() {
    return delLocation(locationIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.$modal.confirm('是否确认导出所有库位信息数据项？').then(() => {
    proxy.$modal.loading("正在导出数据，请稍候...");
    return exportLocation(queryParams.value);
  }).then(response => {
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
    const fileName = '库位信息_' + new Date().getTime() + '.xlsx';
    proxy.$download.saveAs(blob, fileName);
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("导出成功");
  }).catch(() => {
    proxy.$modal.closeLoading();
  });
}

getList();
getWarehouseOptions();  // 获取仓库列表
</script>
